package site.mingdao.boot.common.util.string;

import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

public class SpringContext implements ApplicationContextAware {

    // Spring应用上下文
    @Getter
    private static ApplicationContext applicationContext;

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static String getRequestAttribute(String name) {
        return Objects.requireNonNull(getRequest().getAttribute(name)).toString();
    }

    // 提供一个获取Bean的静态方法
    public static <T> T getBean(Class<T> beanClass) {
        if (applicationContext != null) {
            return applicationContext.getBean(beanClass);
        } else {
            throw new IllegalStateException("ApplicationContext is not initialized yet!");
        }
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

}
